#include "logindialog.h"
#include "ui_logindialog.h"
#include "registerdialog.h"
#include "httpmgr.h"

#include <QCheckBox>
#include <QPixmap>
#include <QPainter>
#include <QPainterPath>
#include <QMessageBox>

LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_login_mod_finish,
            this,&LoginDialog::slot_login_mod_finish);

    //设置图标与标题
    this->setWindowTitle(" ");
    this->setWindowIcon(QIcon(":/images/dog_svg.svg"));

    //输入框提示
    ui->name->setPlaceholderText("请输入账号");
    ui->password->setPlaceholderText("请输入密码");
    ui->password->setEchoMode(QLineEdit::Password);//密码模式
    ui->login->setEnabled(false);

    //绘制圆形头像
    QPixmap pix_avatar(":/images/dog1.png");
    QPixmap pixmap(100,100);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path;
    path.addEllipse(1, 1, 100, 100);
    painter.setClipPath(path);
    painter.drawPixmap(1, 1, 100, 100, pix_avatar);
    ui->avatar->setPixmap(pixmap);

    //设置鼠标悬停在控件上光标变化
    ui->register_btn->setCursor(Qt::PointingHandCursor);
    ui->reset_btn->setCursor(Qt::PointingHandCursor);

    // 创建 QCheckBox 控件（父类选择QLineEdit）
    QCheckBox *checkBox = new QCheckBox(ui->password);
    checkBox->setCursor(Qt::PointingHandCursor);
    // 设置样式表（图片为眼睛样式）
    checkBox->setStyleSheet("QCheckBox {spacing: 5px;border: none;background-color: transparent;}"
                            "QCheckBox::indicator {width: 20px;height: 20px;border: none;image: url(:/images/unvisible.png);}"
                            "QCheckBox::indicator:checked {image: url(:/images/visible.png);}");
    //创建信号和槽连接，控制密码显示方式,stateChanged信号传递int类型
    connect(checkBox, &QCheckBox::stateChanged,this, &LoginDialog::slot_checkbox_state_changed);
    //设置控件的位置（需要根据QLineEdit的坐标进行调整）
    checkBox->setGeometry(ui->password->pos().x() + 250,ui->password->pos().y() + 9,20,20);


    initTitleBar();
}

void LoginDialog::slot_checkbox_state_changed(int state)
{
    if(state){
        ui->password->setEchoMode(QLineEdit::Normal);
    }else{
        ui->password->setEchoMode(QLineEdit::Password);
    }
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::initTitleBar()
{
    this->setWindowFlags(Qt::FramelessWindowHint);
    m_titleBar = new MyTitleBar(this);
    m_titleBar->move(0, 0);
    m_titleBar->setButtonType(ONLY_CLOSE_BUTTON);
    m_titleBar->setTitleIcon("");
    m_titleBar->setBackgroundColor(255, 255, 222,false);
    connect(m_titleBar, &MyTitleBar::signalButtonCloseClicked, this, &LoginDialog::onButtonCloseClicked);

}




void LoginDialog::on_radioButton_clicked(bool checked)
{
    ui->login->setEnabled(checked);
}


void LoginDialog::on_register_btn_clicked()
{
    _register_dlg= new RegisterDialog(this);
    _register_dlg->setAttribute(Qt::WA_DeleteOnClose,true);
    _register_dlg->show();
}


void LoginDialog::on_reset_btn_clicked()
{
    _reset_dlg= new ResetPasswordDialog(this);
    _reset_dlg->show();
}



void LoginDialog::on_login_clicked()
{

    auto nameId = ui->name->text();
    auto password = ui->password->text();
    if( nameId.isEmpty() || password.isEmpty() ){
        QMessageBox::information(this,"输入错误","输入账号或密码为空！");
        return;
    }


    QJsonObject json_obj;
    json_obj["Id"] = ui->name->text().toInt();
    json_obj["Password"] = ui->password->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/toLogin"),
                                        json_obj, ReqId::ID_LOGIN_USER,Modules::LOGINMOD);


}

void LoginDialog::onButtonCloseClicked()
{
    close();
}

void LoginDialog::slot_login_mod_finish(ReqId id, QByteArray res, ErrorCodes err)
{
    if(err == ErrorCodes::ERR_NETWORK){
        QMessageBox::critical(this,"错误","请求发送失败！");
        return;
    }
    if( id == ReqId::ID_LOGIN_USER ){
        QJsonDocument jsonDoc = QJsonDocument::fromJson(res);
        //"code":     0, //  0成功   -1失败
        if ( jsonDoc["code"].toInt() == -1 ){
            QMessageBox::critical(this,"错误",jsonDoc["message"].toString());
            return;
        }
        QJsonObject userData = jsonDoc["userData"].toObject();
        emit sig_login_finish(userData);
    }

}



